#coding=utf-8
#----------------------
#create_date: '12-10-15'
#全局中间件
#----------------------
from django.http import HttpResponseRedirect
from config import tools

__author__ = 'lyhapple'

class LocationMiddleware(object):
    '''根据IP解析用户所在的地区，写入request session,还需写入到cookie
    站内路由，根据IP判断用户所在地区，然后跳转查询,一般用于首次访问时,自动路转到'域名/城市'的URL
    '''
    def process_request(self, request):
        if request.session.has_key("city_en"):
            pass
        else:
            from pub.models import City
            ip = request.META["REMOTE_ADDR"]
            city_cn = tools.ip2locate(ip)
            city_en = tools.locate2host(city_cn)
            try:
                city = City.objects.get(pinyin=city_en)
            except Exception,e:
                city = None
            request.session["city_cn"] = city_cn
            request.session["city_en"] = city_en
            request.session["city"] = city
            #return HttpResponseRedirect(city_en)
